import axios from "axios";

import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);
const myAxios = axios.create({
  baseURL: "http://interview-api-t.itheima.net/",
  timeout: 5000,
});

myAxios.interceptors.request.use(
  (config) => {
    // console.log(config);
    const token = localStorage.getItem("token");
    console.log(token);
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//设置响应拦截
myAxios.interceptors.response.use(
  (response) => {
    // console.log(response);
    return response.data;
  },
  (error) => {
    const {response} = error;
    if(response){
        if(response.status === 400){
            console.log('请求参数错误');
            // alert('登录失败，账号密码错误');
        }else if(response.status === 401){
            console.log('token失效');
            Toast.fail('登录状态失效，请重新登录');
            // alert('请重新登录');
        }else if(response.status === 403){
            console.log('拒绝访问');
        }
        
        return Promise.reject(error);
    }else{
        console.log('请求超时');
    }
  }
);


export default myAxios;